package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.enums.MediaState;
import com.jdy.haoduoai.model.BabyKalaokItem;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.ImageUtils;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.MusicPlayView;
import com.jdy.haoduoai.view.RoundImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import rx.Subscription;

//import com.jdy.haoduoai.R;

@SuppressLint({ "SimpleDateFormat", "HandlerLeak", "InflateParams" })
public class BabyTellStoryDetailActivity extends BaseActivity implements
    OnClickListener/* Callback */{

  @InjectView(id = R.id.shareimgs)
  private ImageView shareimg;
  @InjectView(id = R.id.endtime)
  private TextView endtime;
  @InjectView(id = R.id.usetime)
  private TextView usetime; // 已经播放时
  @InjectView(id = R.id.headicon)
  private RoundImageView headicon;
  @InjectView(id = R.id.editor)
  private TextView editor;
  @InjectView(id = R.id.playtimes)
  private TextView playtimes;
  @InjectView(id = R.id.releasetime)
  private TextView releasetime; // 发布时间
  @InjectView(id = R.id.shareIcon, click = true)
  private TextView shareIcon;

  private ImageView imageCover;

  @InjectView(id = R.id.layout_media_play_view)
  private MusicPlayView mPlayView;
  @InjectView(id = R.id.btn_play_pause, click = true)
  private Button mPlayPause;

  private MediaPlayer mp4Player/* , mp3Player */;
  private MediaState mMediaState = MediaState.Downloaded;

  private String video_url, /* mp3_url, */cover, /* avatar, */username;
  private int idStory, uid, playnums, playtime;
  private BabyKalaokItem mDetailInfoItem = null;
  private DisplayImageOptions options;
  private LeUser mLeUser;

  boolean isPause = true; // 是否已经暂停了
  private Subscription mSubscription;
  private WakeLock mWakeLock;

  private int currentMP4Position;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.babytellstory_detail);

    initialize();
    initListener();
    initHandler();
  }

  @Override
  public void onPause() {
    super.onPause();
    if (mWakeLock != null) {
      mWakeLock.release();
    }

    if (mp4Player != null && mp4Player.isPlaying()) {
      mp4Player.pause();
      currentMP4Position = mp4Player.getCurrentPosition();
      isPause = true;
    }
  }

  @Override
  public void onResume() {
    super.onResume();
    if (mWakeLock != null) {
      mWakeLock.acquire();
    }
  }

  private void initListener() {
    // seekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mSubscription != null) {
      mSubscription.unsubscribe();
    }
    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }
  }

  private void initHandler() {
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);

        if (!Thread.currentThread().isInterrupted()) {
          switch (msg.what) {

          case 5:
            usetime.setText(DateUtils.getTime(playtime / 1000));
            // seekBar.setProgress(playtime / 1000);
            break;

          default:
            break;
          }
        }
      }
    };
  }

  private String getElapseTime(String createdTime) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      Date oldDate = formatter.parse(createdTime);
      Date nowDate = new Date();
      long diff = nowDate.getTime() - oldDate.getTime();
      long seconds = diff / 1000;
      long minutes = seconds / 60;
      long hours = minutes / 60;
      long days = hours / 24;
      if (seconds < 60) {
        return seconds + "秒前";
      } else if (seconds < 3600) {
        return minutes + "分钟前";
      } else if (seconds >= 3600 && seconds < 86400) {
        return hours + "小时前";
      } else {
        return days + "天前";
      }

    } catch (ParseException e) {
      e.printStackTrace();
    }
    return null;
  }

  private void initialize() {

    options = new DisplayImageOptions.Builder().cacheInMemory(true) // 缓存
        .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
        .build();
    mLeUser = ((LeXiaoXiaoBanApp) this.getApplication()).getUser();

    imageCover = (ImageView) mPlayView.findViewById(R.id.avatar);

    if (getIntent().getSerializableExtra("rank_map") != null) {
      mDetailInfoItem = (BabyKalaokItem) getIntent().getSerializableExtra(
          "rank_map");

      if (Tools.isNotEmpty(mDetailInfoItem)) {
        if (mDetailInfoItem.member_id != null) {
          uid = mDetailInfoItem.id;
        }

        setTitle(mDetailInfoItem.dub_name);

        if (mDetailInfoItem.created_at != null) {
          releasetime.setText(getElapseTime(mDetailInfoItem.created_at));
        } else {
          releasetime.setText("");
        }

        if (Tools.isNotEmpty(mDetailInfoItem.dub_cover)) {
          cover = mDetailInfoItem.dub_cover;
        }
      }

      if (Tools.isNotEmpty(cover)) {
        ImageLoader.getInstance().displayImage(cover, imageCover,
            LeXiaoXiaoBanApp.getInstance().getDisplayImageOptions());
      }

      idStory = mDetailInfoItem.id;

      if (mDetailInfoItem.member_nickname != null) {
        username = mDetailInfoItem.member_nickname;
      }

      playnums = mDetailInfoItem.play_count;

      video_url = mDetailInfoItem.av;

      // ImageLoader.getInstance().displayImage(avatar, headicon, options);
      SharedPreferences prefs = this.getSharedPreferences(Constant.USER_INFO,
          Context.MODE_PRIVATE);
      String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");
      Uri BabyUri;
      if (Tools.isNotEmpty(babyImagePath)) {
        BabyUri = Uri.parse(babyImagePath);
        setImageViewContent(headicon, BabyUri);
      } else {
        LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
        if (lb != null) {
          if (lb.gender == 0) {
            headicon.setImageResource(R.drawable.defaut_baby_avtar_female);
          } else {
            headicon.setImageResource(R.drawable.defaut_baby_avtar_male);
          }
        }
      }

      ImageLoader.getInstance().displayImage(cover, shareimg, options);

      editor.setText(username);

      if (Tools.isNotEmpty(mDetailInfoItem.member_id)
          && mDetailInfoItem.member_id.contains(mLeUser.id)) {
        editor.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
      }

      playtimes.setText(playnums + "");

    }
  }

  private Bitmap setImageViewContent(ImageView source, Uri original) {
    if (original != Uri.EMPTY) {
      Bitmap originalBitmap = ImageUtils.getBitmapFromUri(this, original);
      if (originalBitmap != null) {
        Bitmap bm = ImageUtils.scaleCropToFit(originalBitmap, 300, 300, true);
        source.setImageURI(null);
        if (bm != null) {
          source.setImageBitmap(bm);
        }
        return bm;
      }
    }
    return null;
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.back:
      finish();
      break;
    case R.id.btn_play_pause:
      if (mPlayView.isPlay()) {
        mPlayView.pause();
        mPlayPause.setBackgroundResource(R.drawable.playimgs);

        if (mp4Player != null && mp4Player.isPlaying()) {
          mp4Player.pause();
          mMediaState = MediaState.Pause;
          currentMP4Position = mp4Player.getCurrentPosition();
          isPause = true;
        }

      } else {
        mPlayView.play();
        mPlayPause.setBackgroundResource(R.drawable.pauseimgs);

        play();

        // if (mp4Player != null) {
        // mp4Player.start();
        // }

        // Log.i("radio", "clickplay");
        //
        // if (!isPlayInit) {
        // isPlayInit = true;
        // playRadio(playid, "radio");
        // } else {
        // playRadio(playid, "continue");
        // }
      }
      break;
    case R.id.toplays:
      // if (sv_video.isShown()) {
      // if (mMediaState.equals(MediaState.Playing)) {// precondition must be
      // mMediaState = MediaState.Pause;
      // playbtn.setVisibility(View.VISIBLE);
      //
      // if (mp4Player != null && mp4Player.isPlaying()) {
      // mp4Player.pause();
      // currentMP4Position = mp4Player.getCurrentPosition();
      // isPause = true;
      // }
      //
      // } else if (mMediaState.equals(MediaState.Pause)) {
      // mMediaState = MediaState.Playing;
      // playbtn.setVisibility(View.GONE);
      //
      // if (mp4Player != null) {
      // mp4Player.start();
      // }
      // }
      // } else {
      // }
      break;
    case R.id.playbtn:
      // if (mMediaState == MediaState.Pause) {
      // mMediaState = MediaState.Playing;
      // playbtn.setVisibility(View.GONE);
      //
      // if (mp4Player != null) {
      // mp4Player.start();
      // new Thread(new UIUpdateThread()).start();
      // }
      // } else {
      // play();
      // }

      break;
    case R.id.shareIcon:
      Intent intent = new Intent(this, SharePopupWindow.class);
      intent.putExtra("pic", cover);
      intent.putExtra("name", mDetailInfoItem.dub_name);
      intent.putExtra("av", mDetailInfoItem.av); // 音频

      if (Tools.isNotEmpty(mDetailInfoItem.catalog)
          && mDetailInfoItem.catalog.contains("kalaok")) {
        intent.putExtra("share_data", "宝宝唱的卡拉ok");
      } else {
        intent.putExtra("share_data", "宝宝讲的故事");
      }

      startActivity(intent);

      break;

    default:
      break;
    }

  }

  /**
   * 播放
   */
  private void play() {
    if (isPause) {

      if (mp4Player != null) {
        mp4Player.seekTo(currentMP4Position);
        mp4Player.start();
        isPause = false;

        new Thread(new UIUpdateThread()).start();

      } else {
        new AsyncTask<Void, Void, Void>() {

          @Override
          protected void onPreExecute() {
            // playbtn.setVisibility(View.GONE);
          }

          @Override
          protected Void doInBackground(Void... params) {
            mp4Player = new MediaPlayer();
            // mp4Player.setDisplay(surfaceHolder);
            mp4Player.setOnCompletionListener(new OnCompletionListener() {
              @Override
              public void onCompletion(MediaPlayer arg0) {
                if (mp4Player != null) {
                  mp4Player.release();
                  mp4Player = null;
                }
              }
            });
            mp4Player.setOnErrorListener(new OnErrorListener() {
              @Override
              public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
                if (mp4Player != null) {
                  mp4Player.release();
                  mp4Player = null;
                }
                return false;
              }
            });
            try {
              mp4Player.setDataSource(video_url);
              mp4Player.prepare();
              mp4Player.seekTo(currentMP4Position);
              mp4Player.start();

              isPause = false;

              mMediaState = MediaState.Playing;
            } catch (Exception e) {
              e.printStackTrace();
            }
            return null;
          }

          @Override
          protected void onPostExecute(Void result) {

            if (Tools.isNotEmpty(mp4Player)) {
              // seekBar.setMax(mp4Player.getDuration() / 1000);
              endtime.setText(" / "
                  + DateUtils.getTime(mp4Player.getDuration() / 1000));
              new Thread(new UIUpdateThread()).start();
            }
          }

        }.execute((Void[]) null);
      }

    } else {
      // 判断视频 是否为播放状态
      if (mp4Player != null) {
        if (mp4Player.isPlaying()) {
          System.out.println("视频处于播放状态");
        }
      } else {
        // playbtn.setVisibility(View.GONE);
        // sv_video.setVisibility(View.VISIBLE);
        // surfaceHolder = sv_video.getHolder();
        // surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // surfaceHolder.addCallback(this);
      }
    }
  }

  private class UIUpdateThread implements Runnable {
    long time = 500; // 滚动速度

    @Override
    public void run() {
      while (mp4Player != null && mp4Player.isPlaying()) {
        playtime = mp4Player.getCurrentPosition();

        if (handler != null) {
          handler.sendEmptyMessage(5);
        }

        try {
          Thread.sleep(time);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  private class SeekBarChangeEvent implements OnSeekBarChangeListener {
    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
      // 开始拖动进度条
      // isChanging = true;
    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {

      if (mp4Player != null) {
        mp4Player.seekTo(arg0.getProgress());
      }

      // isChanging = false;

      if (mp4Player != null && mp4Player.isPlaying()) {
        mp4Player.seekTo(arg0.getProgress() * 1000);
        mp4Player.start();
      }
    }
  }

}
